package cn.nange.cmfz.aspect;

import cn.nange.cmfz.annotation.LogAnnotation;
import cn.nange.cmfz.entity.Admin;
import cn.nange.cmfz.entity.AdminLog;
import cn.nange.cmfz.service.AdminLogService;
import cn.nange.cmfz.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class AdminLogAop {
    /**
     * 切点
     * 切方法
     * 切注解 更加灵活
     */

    @Autowired
    private AdminLogService logAdminService;

    @Pointcut("@annotation(cn.nange.cmfz.annotation.LogAnnotation)")

    public void LogAdminPointcut() {
    }

    @After("LogAdminPointcut()")
    public void logAdminAfter(JoinPoint joinPoint) {
//        获取日志数据
        AdminLog logAdmin = new AdminLog();

        logAdmin.setLogDate(new Date());
//        获取admin的id 从session
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();

        Admin admin = (Admin) session.getAttribute("admin");

        System.out.println("admin = " + admin);

        logAdmin.setAdminId(admin.getId());

//        获取 IP

        logAdmin.setIp(IPKit.getIpAddrByRequest(request));

        System.out.println(IPKit.getIpAddrByRequest(request));

        /**
         * LogContent
         * 执行了一个查询上师的方法 content内容应该是：查询上师
         * 执行了一个删除上师的方法 content内容应该是：删除上师
         *
         * 执行的方法不同 内容和type都不一样
         *
         * 自定义注解
         */
//        获取注解的值
//        1.获取方法签名对象

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //        2.获取方法对象

        Method method = signature.getMethod();

        //        3.获取方法上的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);

        //        4.获取注解的值
        logAdmin.setLogContent(annotation.content());
        logAdmin.setLogType(annotation.type());

        /**
         * 添加数据库
         */
        logAdminService.add(logAdmin);

    }
}
